<template>
	<view class="fix-top-window">
		<view class="uni-header">
			<view class="uni-group">
				<input 
					class="uni-search" 
					type="text" 
					v-model="query" 
					@confirm="handleSearch" 
					:placeholder="$t('common.placeholder.query')" 
				/>
				<button 
					class="uni-button hide-on-phone" 
					type="default" 
					size="mini" 
					@click="handleSearch"
				>
					{{ $t('common.button.search') }}
				</button>
				<button 
					class="uni-button" 
					type="primary" 
					size="mini" 
					@click="handleOpenForm('add')"
				>
					{{ $t('common.button.add') }}
				</button>
				<button 
					class="uni-button" 
					type="warn" 
					size="mini" 
					:disabled="!selectedIndexs.length"
					@click="handleBatchDelete"
				>
					{{ $t('common.button.batchDelete') }}
				</button>
				<!-- #ifdef H5 -->
				<download-excel 
					class="hide-on-phone" 
					:fields="exportExcel.fields" 
					:data="exportExcelData"
					:type="exportExcel.type" 
					:name="exportExcel.filename"
				>
					<button class="uni-button" type="primary" size="mini">
						{{ $t('common.button.exportExcel') }}
					</button>
				</download-excel>
				<!-- #endif -->
			</view>
		</view>
		<view class="uni-container">
			<uni-table 
				ref="tableRef" 
				:loading="loading" 
				:emptyText="error || $t('common.empty')" 
				border 
				stripe
				type="selection" 
				@selection-change="handleSelectionChange"
			>
					<uni-tr>
					<uni-th 
						align="center" 
						filter-type="search" 
						@filter-change="(e) => handleFilterChange(e, 'role_id')"
						sortable 
						@sort-change="(e) => handleSortChange(e, 'role_id')"
					>
						唯一ID
					</uni-th>
					<uni-th 
						align="center" 
						filter-type="search" 
						@filter-change="(e) => handleFilterChange(e, 'role_name')"
						sortable 
						@sort-change="(e) => handleSortChange(e, 'role_name')"
					>
						名称
					</uni-th>
						<uni-th align="center">权限</uni-th>
					<uni-th 
						align="center" 
						filter-type="search" 
						@filter-change="(e) => handleFilterChange(e, 'comment')"
						sortable 
						@sort-change="(e) => handleSortChange(e, 'comment')"
					>
						备注
					</uni-th>
					<uni-th 
						align="center" 
						filter-type="timestamp"
						@filter-change="(e) => handleFilterChange(e, 'create_date')" 
						sortable
						@sort-change="(e) => handleSortChange(e, 'create_date')"
					>
						创建时间
					</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
				<uni-tr v-for="(item, index) in dataList" :key="item._id || index">
					<uni-td align="center">{{ item.role_id }}</uni-td>
					<uni-td align="center">{{ item.role_name }}</uni-td>
					<uni-td align="center">{{ item.permission_display || (item.permission && item.permission.join('、')) }}</uni-td>
					<uni-td align="center">{{ item.comment }}</uni-td>
						<uni-td align="center">
							<uni-dateformat :threshold="[0, 0]" :date="item.create_date"></uni-dateformat>
						</uni-td>
						<uni-td align="center">
							<view class="uni-group">
							<button 
								@click="handleOpenForm('edit', item)" 
								class="uni-button" 
								size="mini"
								type="primary"
							>
								{{ $t('common.button.edit') }}
							</button>
							<button 
								@click="handleConfirmDelete(item._id)" 
								class="uni-button" 
								size="mini"
								type="warn"
							>
								{{ $t('common.button.delete') }}
							</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
				<uni-pagination 
					show-icon 
					show-page-size 
					:page-size="pagination.size" 
					v-model="pagination.current"
					:total="pagination.count" 
					@change="handlePageChanged" 
					@pageSizeChange="handleChangeSize" 
				/>
			</view>
		</view>
		
		<!-- 新增/编辑弹窗 -->
		<uni-popup ref="formPopup" type="center" :mask-click="false">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">{{ formMode === 'add' ? '新增角色' : '编辑角色' }}</text>
					<text class="popup-close" @click="handleCloseForm">×</text>
				</view>
				<view class="popup-body">
					<uni-forms ref="formRef" :value="formData" :rules="formRules" validateTrigger="bind">
						<uni-forms-item name="role_id" label="唯一ID" required>
							<uni-easyinput 
								placeholder="角色唯一标识，不可修改，不允许重复" 
								v-model="formData.role_id" 
								trim="both"
								:disabled="formMode === 'edit'"
							></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="role_name" label="名称" required>
							<uni-easyinput 
								placeholder="角色名称" 
								v-model="formData.role_name" 
								trim="both"
							></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="permission" label="权限" class="flex-center-x">
							<uni-data-checkbox 
								:multiple="true" 
								v-model="formData.permission" 
								collection="uni-id-permissions" 
								:page-size="500" 
								field="permission_name as text, permission_id as value"
							></uni-data-checkbox>
						</uni-forms-item>
						<uni-forms-item name="comment" label="备注">
							<uni-easyinput 
								type="textarea" 
								placeholder="备注" 
								v-model="formData.comment" 
								trim="both"
							></uni-easyinput>
						</uni-forms-item>
					</uni-forms>
				</view>
				<view class="popup-footer">
					<button type="primary" class="uni-button" @click="handleSubmitForm">
						{{ $t('common.button.submit') }}
					</button>
					<button class="uni-button" @click="handleCloseForm" style="margin-left: 15px;">
						{{ $t('common.button.cancel') }}
					</button>
				</view>
		</view>
		</uni-popup>
		
		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue'
	import { useI18n } from 'vue-i18n'
	import { getList, add, update, remove, getDetail, handleResponse } from '@/js_sdk/uni-admin/crud.js'
	import { validator } from '@/js_sdk/validator/uni-id-roles.js'

	// 国际化
	const { t } = useI18n()

	// 获取全局属性
	const vk = uni.vk

	// 分页配置常量
	const PAGE_SIZE = 20
	const PAGE_CURRENT = 1

	// 排序映射
	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	// 响应式数据
	const dataList = ref([])
	const query = ref('')
	const selectedIndexs = ref([])
	const loading = ref(false)
	const error = ref('')
	const tableRef = ref(null)
	const formPopup = ref(null)
	const formRef = ref(null)

	// 表单相关
	const formMode = ref('add') // add | edit
	const formDataId = ref('')
	const formData = reactive({
		role_id: "",
		role_name: "",
		permission: [],
		comment: "",
		create_date: null
	})

	// 表单验证规则
	function getFormRules() {
		const fields = Object.keys(formData)
		const rules = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				rules[key] = validator[key]
			}
		}
		return rules
	}
	const formRules = getFormRules()

	// 分页数据
	const pagination = reactive({
		current: PAGE_CURRENT,
		size: PAGE_SIZE,
		count: 0
	})

	// 查询参数
	const queryParams = reactive({
		pageIndex: PAGE_CURRENT,
		pageSize: PAGE_SIZE,
		keyword: '',
		orderBy: 'create_date',
		orderType: 'desc'
	})

	// 导出Excel配置
	const exportExcel = reactive({
		filename: "uni-id-roles.xls",
		type: "xls",
		fields: {
						"唯一ID": "role_id",
						"名称": "role_name",
			"权限": "permission_display",
						"备注": "comment",
						"create_date": "create_date"
					}
	})

	const exportExcelData = ref([])

	// 加载数据
	const loadData = async () => {
		loading.value = true
		error.value = ''
		
		try {
			const res = await getList('role', {
				pageIndex: pagination.current,
				pageSize: pagination.size,
				keyword: queryParams.keyword,
				orderBy: queryParams.orderBy,
				orderType: queryParams.orderType
			})
			
			if (res.code === 0) {
				dataList.value = res.data.list || []
				pagination.count = res.data.total || 0
				
				// 处理导出数据
				exportExcelData.value = dataList.value.map(item => ({
					...item,
					permission_display: item.permission_display || (item.permission && item.permission.join('、'))
				}))
			} else {
				error.value = res.msg || '加载失败'
				vk.toast(res.msg || '加载失败')
			}
		} catch (err) {
			error.value = err.msg || '加载失败'
			vk.toast(err.msg || '加载失败')
		} finally {
			loading.value = false
		}
	}

	// 搜索
	const handleSearch = () => {
		queryParams.keyword = query.value.trim()
		pagination.current = 1
		loadData()
				}

	// 分页改变
	const handlePageChanged = (e) => {
		selectedIndexs.value = []
		if (tableRef.value) {
			tableRef.value.clearSelection()
		}
		pagination.current = e.current
		loadData()
	}

	// 改变每页数量
	const handleChangeSize = (pageSize) => {
		pagination.size = pageSize
		pagination.current = 1
		loadData()
	}

	// 排序改变
	const handleSortChange = (e, name) => {
		if (e.order) {
			queryParams.orderBy = name
			queryParams.orderType = orderByMapping[e.order] || 'desc'
		} else {
			queryParams.orderBy = 'create_date'
			queryParams.orderType = 'desc'
		}
		if (tableRef.value) {
			tableRef.value.clearSelection()
		}
		loadData()
	}

	// 筛选改变
	const handleFilterChange = (e, name) => {
		if (e.filter && e.filter.length > 0) {
			queryParams.keyword = e.filter[0]
		} else {
			queryParams.keyword = ''
		}
		pagination.current = 1
		loadData()
	}

	// 打开表单弹窗
	const handleOpenForm = async (mode, item = null) => {
		formMode.value = mode
		
		// 重置表单
		formData.role_id = ""
		formData.role_name = ""
		formData.permission = []
		formData.comment = ""
		formData.create_date = null
		formDataId.value = ""
		
		if (mode === 'edit' && item) {
			formDataId.value = item._id
			// 加载详情
			uni.showLoading({ mask: true })
			try {
				const res = await getDetail('role', item._id)
				handleResponse(res, (data) => {
					if (data) {
						Object.assign(formData, {
							role_id: data.role_id || "",
							role_name: data.role_name || "",
							permission: data.permission || [],
							comment: data.comment || "",
							create_date: data.create_date || null
				})
					}
				})
			} catch (err) {
				vk.toast(err.msg || '加载失败')
			} finally {
				uni.hideLoading()
			}
		}
		
		// 打开弹窗
		if (formPopup.value) {
			formPopup.value.open()
		}
	}

	// 关闭表单弹窗
	const handleCloseForm = () => {
		if (formPopup.value) {
			formPopup.value.close()
		}
		// 重置表单验证
		if (formRef.value) {
			formRef.value.clearValidate()
		}
	}

	// 提交表单
	const handleSubmitForm = async () => {
		if (!formRef.value) return
		
		uni.showLoading({ mask: true })
		
		try {
			await formRef.value.validate()
			
			const submitData = { ...formData }
			
			if (formMode.value === 'add') {
				const res = await add('role', submitData)
				handleResponse(res, () => {
					vk.toast('新增成功')
					handleCloseForm()
					loadData()
				})
			} else {
				const res = await update('role', formDataId.value, submitData)
				handleResponse(res, () => {
					vk.toast('修改成功')
					handleCloseForm()
					loadData()
				})
			}
		} catch (err) {
			if (err.msg) {
				vk.toast(err.msg)
						}
		} finally {
			uni.hideLoading()
		}
	}

	// 获取选中的项
	const getSelectedItems = () => {
		return selectedIndexs.value.map(i => dataList.value[i]._id)
	}

			// 批量删除
	const handleBatchDelete = async () => {
		const ids = getSelectedItems()
		if (!ids || ids.length === 0) {
			vk.toast('请选择要删除的角色')
			return
		}
		
		uni.showModal({
			title: '提示',
			content: '确定要删除选中的角色吗？',
			success: async (res) => {
				if (!res.confirm) return
				
				try {
					const result = await remove('role', ids)
					handleResponse(result, () => {
						vk.toast('删除成功')
						if (tableRef.value) {
							tableRef.value.clearSelection()
					}
						loadData()
				})
				} catch (err) {
					vk.toast(err.msg || '删除失败')
				}
			}
		})
	}

	// 多选改变
	const handleSelectionChange = (e) => {
		selectedIndexs.value = e.detail.index
	}

	// 确认删除
	const handleConfirmDelete = async (id) => {
		uni.showModal({
			title: '提示',
			content: '确定要删除该角色吗？',
			success: async (res) => {
				if (!res.confirm) return
				
				try {
					const result = await remove('role', id)
					handleResponse(result, () => {
						vk.toast('删除成功')
						if (tableRef.value) {
							tableRef.value.clearSelection()
						}
						loadData()
				})
				} catch (err) {
					vk.toast(err.msg || '删除失败')
				}
			}
		})
	}

	// uni-app 页面生命周期
	const onLoad = (options = {}) => {
		loadData()
	}

	const onReady = () => {
		if (dataList.value.length === 0 && !loading.value) {
			loadData()
		}
	}
</script>

<style scoped>
	.popup-content {
		width: 600px;
		max-width: 90vw;
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px 20px;
		border-bottom: 1px solid #eee;
	}

	.popup-title {
		font-size: 16px;
		font-weight: bold;
	}

	.popup-close {
		font-size: 24px;
		color: #999;
		cursor: pointer;
		line-height: 1;
	}

	.popup-body {
		padding: 20px;
		max-height: 60vh;
		overflow-y: auto;
	}

	.popup-footer {
		display: flex;
		justify-content: flex-end;
		padding: 15px 20px;
		border-top: 1px solid #eee;
	}

	::v-deep .uni-forms-item__label {
		width: 90px !important;
	}
</style>
